package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MapDao;
import com.itheima.dao.OrderDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = MapService.class)
@Transactional
public class MapServiceImpl implements MapService {

    //依赖注入MapDao
    @Autowired
    private MapDao mapDao;

    @Autowired
    private OrderDao orderDao;

    //查询数据库地址
    @Override
    public List<Address> findAddress() {
        List<Address> addresses = mapDao.findAddress();
        return addresses;
    }

    //分页查询
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        //分页助手
        PageHelper.startPage(currentPage, pageSize);
        Page<Address> page = mapDao.selectByCondition(queryString);

        return new PageResult(page.getTotal(), page.getResult());
    }

    //新增地址项
    @Override
    public Map add(Address address) {
        Map map = new HashMap();
        //查询已添加地址名
        List<String> names = mapDao.findAddressNames();
        for (String name : names) {
            if (name.equals(address.getAddress()) && names != null) {
                map.put("flag", false);
                map.put("message", "该地址已存在请勿重复添加");
                return map;
            }
        }
        mapDao.add(address);
        map.put("flag", true);
        map.put("message", "地址添加成功");
        return map;

    }

    //删除地址项
    @Override
    public Map deleteById(Integer id) {

        Map map = new HashMap();

        String addressName = mapDao.findAddressNameById(id);
        List<String> names = orderDao.findOrderAddressNames();
        for (String name : names) {
            if (addressName.equals(name) && names != null && names.size() != 0) {
                map.put("flag", false);
                map.put("message", "该地址有预约人员,无法删除");
                return map;
            }
        }

        mapDao.deleteById(id);
        map.put("flag", true);
        map.put("message", "删除地址成功");
        return map;
    }

    @Override
    public List<Map<String, Integer>> findList() {
        return mapDao.findList();
    }
}
